'''
改写果壳登录验证码是别的代码
'''
# -*- coding: utf-8 -*-
from base64 import b64encode
import requests
import scrapy
import time
from PIL import Image
from scrapy.http import FormRequest, Request
from io import BytesIO
import pytesseract


class GuokeLogin2Spider(scrapy.Spider):
    name = 'guoke_login2'
    allowed_domains = ['guokr.com']
    start_urls = ['https://www.guokr.com/']
    login_url = 'https://account.guokr.com/sign_in/'

    def start_requests(self):
        # dont_filter=True不过滤多次请求页面
        yield Request(self.login_url, callback=self.login, dont_filter=True)

    def parse(self, response):
        print('解析成功')

    def login(self, response):
        login_response = response.meta.get('login_response')

        if not login_response:
            # 此时response为登录页响应，是用来获取验证码地址的
            captcha_url = response.xpath('//img[@id="captchaImage"]/@src').get()
            captcha_url = response.urljoin(captcha_url)
            yield Request(captcha_url, callback=self.login, meta={'login_response': response}, dont_filter=True)
        else:
            # 此时response为验证码响应，response.body为二进制数据
            print('=' * 30)
            username = '18106951237'
            password = '951237'
            permanent = 'y'

            formdata = {
                'username': username,
                'password': password,
                'permanent': permanent
            }
            captcha = self.recognize_captcha_user(response.body)
            if not captcha:
                return scrapy.Request(url=self.start_urls[0], callback=self.parse)
            else:
                formdata['captcha'] = captcha
                print(formdata['captcha'])
            # 不能有相同的url会过滤掉
            # ?????????????????????
            # 默认会获取隐藏的对象，所以这里就不要传递隐藏对象
            # yield FormRequest.from_response(response, formid="loginForm", formdata=formdata, callback=self.parse_page)
            yield FormRequest.from_response(login_response, formdata=formdata, callback=self.parse_login)

    # 手动验证码识别
    def recognize_captcha_ORC(self, data):
        # ORC识别
        image = Image.open(BytesIO(data))
        image = image.convert('L')
        captcha = pytesseract.image_to_string(image)
        image.close()
        return captcha

    # 平台验证码识别
    def recognize_captcha_network(self, data):
        # 识别长度为4任意数字英文字母的验证码
        # request.urlretrieve(captcha_utl, 'captcha.png')
        host = 'https://302307.market.alicloudapi.com'
        path = '/ocr/captcha'
        recognize_url = host + path
        form_data = {'length': 4}
        # with open('captcha.png', 'rb') as fp:
        #     data = fp.read()
        #     image = b64encode(data)
        #     form_data['image'] = image
        image = b64encode(data)
        form_data['image'] = image
        form_data['type'] = 1001
        appcode = '50e4ccb3521f4f8bb02b68a492ec8ec7'
        headers = {
            'Authorization': 'APPCODE ' + appcode,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        response = requests.post(recognize_url, data=form_data, headers=headers)
        result = response.json()
        print(result)
        # 加一个判断是否解析成功
        if result['code'] == 0:
            return result['data']['captcha']
        else:
            return ''

    def recognize_captcha_user(self, data):
        image = Image.open(BytesIO(data))
        image.show()
        captcha = input("请输入验证码：")
        image.close()
        return captcha

    def parse_login(self, response):
        time.sleep(1)
        print(response.text)
        print('=' * 30)
        print(response.url)
        if response.url == 'https://account.guokr.com/sign_in/':
            content = response.xpath('//head/meta[@http-equiv="Refresh"]/@content').get()
            # print(type(content))
            # print(content)
            url = str(content)[3:]
            print(url)
            yield Request(url, callback=self.parse_guokr_page)

        else:
            print("登录失败")
            return self.start_requests()

    def parse_guokr_page(self, response):
        title = response.xpath('//head/title/text()').get()
        if title == '果壳 科技有意思':
            print('登录成功')
            return super().start_requests()
        else:
            print("登录失败")
            return self.start_requests()
